package message.base;

import message.annotation.MsgHandler;
import message.handler.IMsgHandler;
import org.reflections.Reflections;

import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import static org.reflections.scanners.Scanners.SubTypes;
import static org.reflections.scanners.Scanners.TypesAnnotated;

public class HandlerManager {

    private static Map<String, Class> handlers;

    static {
        loadHandler();
    }

    public static HandlerManager getDefault(){
        return HandlerManagerInstance.instance;
    }

    private static void loadHandler(){
        Reflections reflections = new Reflections("message.handler");
        Set<Class<?>> annotated =
                reflections.get(SubTypes.of(TypesAnnotated.with(MsgHandler.class)).asClass());
        handlers = new ConcurrentHashMap<String, Class>();
        for (Class<?> classObject : annotated) {
            MsgHandler sys = (MsgHandler) classObject.getAnnotation(message.annotation.MsgHandler.class);
            handlers.put(sys.name(), classObject);
        }
        handlers = Collections.unmodifiableMap(handlers);
    }

    public IMsgHandler getHandler(String handlerName) throws Exception {
        if (handlers.containsKey(handlerName)) {
            try {
                IMsgHandler handler = (IMsgHandler) handlers.get(handlerName).newInstance();
                return handler;
            } catch (InstantiationException | IllegalAccessException ex) {
                //
                throw new Exception("获取【"+handlerName+"】失败");
            }
        } else {
            // 抛出异常，此系统未实现  sysName
            throw new Exception("获取【"+handlerName+"】失败");
        }
    }

    public static class HandlerManagerInstance {
        private static final HandlerManager instance = new HandlerManager();

        public HandlerManagerInstance(){
        }
    }
}
